const childProcess = require("child_process");
const iconv = require("iconv-lite");

function Ping() {
  this.pingCallback = null;
}

Ping.prototype.start = function(address, callback) {
  let process = childProcess.spawn("ping", [address]);
  let pingTimes = 0;
  let res = "";
  this.pingCallback = callback;
  process.stdout.on("data", data => {
    let str = iconv.decode(data, "cp936");
    res += str;
  });
  process.stderr.on("data", data => {
    res = data;
    this.pingCallback(res);
  });
  process.on("close", code => {
    const data = res.split("\r\n");
    const result = { result: res };
    if (data.length >= 12) {
      result['test1'] = data[2];
      result['test2'] = data[3];
      result['test3'] = data[4];
      result['test4'] = data[5];
      result['result'] = data[8] + data[10];
    }
    this.pingCallback(result);
  });
}

const ping = new Ping();

export default ping;